<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>更换头像</span>
    </div>
    <div>
      <img v-if="!avatar" class="the_img" src="../../assets/images/avatar.jpg" alt="" />
      <img v-else :src="avatar" alt=""  class="the_img" >
      <!-- 按钮区域 -->
      <div class="btn-box">
        <!-- accept="image/*"来规定能够上传的文件类型 -->
        <!-- 监听input的value值,当它的value有变化时,在失去焦点后触发change事件。 -->
        <input
          type="file"
          accept="image/*"
          style="display: none"
          ref="iptRef"
          @change="onFileChange"
        />
        <el-button type="primary" icon="el-icon-plus" @click="chooseImg">选择图片</el-button>
        <el-button type="success" icon="el-icon-upload" :disabled="avatar === ''" @click="uploadFn">上传头像</el-button>
      </div>
    </div>
  </el-card>
</template>

<script>
import { updateuserAvatarAPI } from '@/api'
export default {
  name: 'UserAvatar',
  data () {
    return {
      avatar: ''
    }
  },
  methods: {
    chooseImg () {
      this.$refs.iptRef.click()
    },
    onFileChange (e) { // e原生事件对象
      const files = e.target.files
      if (files.length === 0) {
        this.avatar = ''
      } else {
        console.log(files[0])
        // this.avatar = URL.createObjectURL(files[0]0)
        const fr = new FileReader()
        fr.readAsDataURL(files[0])
        fr.onload = (e) => {
          this.avatar = e.target.result
        }
      }
    },
    async uploadFn () {
      const { data: res } = await updateuserAvatarAPI(this.avatar)
      if (res.code !== 0) return this.$message.error(res.message)
      this.$message.success(res.message)
      this.$store.dispatch('getUserInfoActions')
    }
  }
}
</script>

<style lang="less" scoped>
.btn-box{
  margin-top: 10px;
}
.preview{
  object-fit: cover;  //防止图片挤压变形
}
.the_img{
  width: 350px;
  height: 350px;
}
</style>
